﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		TagRepository.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            TagRepository.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Collections.Generic;
using System.Linq;
using Dexter.Core.Data.Repository;
using Dexter.DataTransferObject;
using Dexter.Domain.Model;
using Dexter.Domain.Results;
using Dexter.Logger.Contracts;
using Dexter.Repository.NHibernate.Queries;
using NHibernate;
using NHibernate.Criterion;
using Topics.Radical.Validation;
using ISessionFactory = Dexter.Repository.NHibernate.SessionFactory.ISessionFactory;

namespace Dexter.Repository.NHibernate.Repositories
{
	/// <summary>
	/// The implementation of <see cref="ITagRepository"/>:
	/// </summary>
	/// <example>The following is an example of initializing 
	///          an <c>TagRepository</c> type:
	///   <code>
	///       // Create the type.
	///       TagRepository ds = new TagRepository;
	/// 
	///       if ( null == ds )
	///           return;
	/// 
	///       return ds.DoSomething( 5 );
	///   </code>
	/// </example>
	public class TagRepository : RepositoryBase<TagItem>, ITagRepository
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="TagRepository"/> class.
		/// </summary>
		/// <param name="sessionFactory">The session factory.</param>
		/// <param name="logger">The logger.</param>
		public TagRepository ( ISessionFactory sessionFactory , ILogger logger ) : base ( sessionFactory , logger ) {}

		/// <summary>
		/// Retireve a paged list of approved item, filtered by tag.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="tagName">The tag name.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		/// <exception cref="ArgumentNullException"> If <paramref name="tagName"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual IPagedResult<Item> GetItemsByTag ( int pageIndex, int pageSize, string tagName ) {
			return GetItemsByTag ( pageIndex , pageSize , tagName , false );
		}

		/// <summary>
		/// Retireve a paged list of approved item, filtered by tag.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="tagName">The tag name.</param>
		/// <param name="includeFuturesPosts">if set to <c>true</c> the result will include the tags used in futures <see cref="Post"/>.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		/// <exception cref="ArgumentNullException"> If <paramref name="tagName"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual IPagedResult<Item> GetItemsByTag ( int pageIndex, int pageSize, string tagName, bool includeFuturesPosts ) {
			return GetItemsByTag(pageIndex, pageSize, tagName, false,true);
		}

		/// <summary>
		/// Retireve a paged list of approved item, filtered by tag.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="tagName">The tag name.</param>
		/// <param name="includeFuturesPosts">if set to <c>true</c> the result will include the tags used in futures <see cref="Post"/>.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		/// <exception cref="ArgumentNullException"> If <paramref name="tagName"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual IPagedResult<Item> GetItemsByTag ( int pageIndex, int pageSize, string tagName, bool includeFuturesPosts, bool enableTracking ) {
			Ensure.That(pageIndex)
				.Named("pageIndex")
				.WithPreview((v, e) => Logger.Warn(v.GetFullErrorMessage(), e))
				.IsGreaterThen(0, Or.Equal)
				.WithMessage("Invalid page index.");

			Ensure.That(pageSize)
				.Named("pageSize")
				.WithPreview((v, e) => Logger.Warn(v.GetFullErrorMessage(), e))
				.IsGreaterThen(0)
				.WithMessage("Invalid page size.");

			Ensure.That(tagName)
				.Named("tagName")
				.WithPreview((v, e) => Logger.Warn(v.GetFullErrorMessage(), e))
				.IsNotNullNorEmpty (  )
				.WithMessage("Invalid tag name.");

			IFutureValue<long> total = Session.GetNamedQuery(KnownQueries.TagRepository.GetItemsByTagCount)
				.SetParameter("publishDate", !includeFuturesPosts
													? DateTime.Now
													: DateTime.Now.AddYears(1000))
				.SetParameter("tagName",tagName)
				.SetFirstResult(pageIndex * pageSize)
				.FutureValue<long>();

			IEnumerable<Item> result = Session.GetNamedQuery(KnownQueries.TagRepository.GetItemsByTag)
				.SetParameter("publishDate", !includeFuturesPosts
													? DateTime.Now
													: DateTime.Now.AddYears(1000))
				.SetParameter("tagName", tagName)
				.SetFirstResult(pageIndex * pageSize)
				.SetMaxResults(pageSize)
				.SetReadOnly(!enableTracking)
				.Future<Item>();

			return new PagedResult<Item>(pageIndex, pageSize, result.ToList(), total.Value);
		}

		/// <summary>
		/// Retireve a paged list of approved posts, filtered by tag.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="tagName">The tag name.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		/// <exception cref="ArgumentNullException"> If <paramref name="tagName"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual IPagedResult<Post> GetPostsByTag ( int pageIndex, int pageSize, string tagName ) {
			return GetPostsByTag ( pageIndex, pageSize, tagName, false );
		}

		/// <summary>
		/// Retireve a paged list of approved posts, filtered by tag.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="tagName">The tag name.</param>
		/// <param name="includeFuturesPosts">if set to <c>true</c> the result will include the tags used in futures <see cref="Post"/>.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		/// <exception cref="ArgumentNullException"> If <paramref name="tagName"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual IPagedResult<Post> GetPostsByTag ( int pageIndex, int pageSize, string tagName, bool includeFuturesPosts ) {
			return GetPostsByTag ( pageIndex, pageSize, tagName, false, true );
		}

		/// <summary>
		/// Retireve a paged list of approved posts, filtered by tag.
		/// </summary>
		/// <param name="pageIndex">Index of the page (0 based).</param>
		/// <param name="pageSize">The number of items to retrieve.</param>
		/// <param name="tagName">The tag name.</param>
		/// <param name="includeFuturesPosts">if set to <c>true</c> the result will include the tags used in futures <see cref="Post"/>.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		/// <exception cref="ArgumentNullException"> If <paramref name="tagName"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual IPagedResult<Post> GetPostsByTag ( int pageIndex, int pageSize, string tagName, bool includeFuturesPosts, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0, Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			Ensure.That ( tagName )
				.Named ( "tagName" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsNotNullNorEmpty ( )
				.WithMessage ( "Invalid tag name." );

			IFutureValue<long> total = Session.GetNamedQuery ( KnownQueries.TagRepository.GetPostsByTagCount )
				.SetParameter ( "publishDate", !includeFuturesPosts
													? DateTime.Now
													: DateTime.Now.AddYears ( 1000 ) )
				.SetParameter ( "tagName", tagName )
				.SetFirstResult ( pageIndex * pageSize )
				.FutureValue<long> ( );

			IEnumerable<Post> result = Session.GetNamedQuery ( KnownQueries.TagRepository.GetPostsByTag )
				.SetParameter ( "publishDate", !includeFuturesPosts
													? DateTime.Now
													: DateTime.Now.AddYears ( 1000 ) )
				.SetParameter ( "tagName", tagName )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future<Post> ( );

			return new PagedResult<Post> ( pageIndex, pageSize, result.ToList ( ), total.Value );
		}

		/// <summary>
		/// Retrieve the top used tags for all approved items.
		/// </summary>
		/// <param name="numberOfItemsToRetireve">The number of items to retireve.</param>
		/// <returns>
		/// Return a list of <see cref="TagItem"/>.
		/// The return item could be null if there isn't items into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="numberOfItemsToRetireve"/> is lesser than 1.</exception>
		public virtual IList<TagDto> GetTopTags(int numberOfItemsToRetireve)
		{
			return GetTopTags ( numberOfItemsToRetireve , false );
		}

		/// <summary>
		/// Retrieve the top used tags for all approved items.
		/// </summary>
		/// <param name="numberOfItemsToRetireve">The number of items to retireve.</param>
		/// <param name="includeFuturesPosts">if set to <c>true</c> the result will include the tags used in futures <see cref="Post"/>.</param>
		/// <returns>
		/// Return a list of <see cref="TagItem"/>.
		/// The return item could be null if there isn't items into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="numberOfItemsToRetireve"/> is lesser than 1.</exception>
		public virtual IList<TagDto> GetTopTags(int numberOfItemsToRetireve, bool includeFuturesPosts)
		{
			return GetTopTags ( numberOfItemsToRetireve , false , true );
		}

		/// <summary>
		/// Retrieve the top used tags for all approved items.
		/// </summary>
		/// <param name="numberOfItemsToRetireve">The number of items to retireve.</param>
		/// <param name="includeFuturesPosts">if set to <c>true</c> the result will include the tags used in futures <see cref="Post"/>.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// Return a list of <see cref="TagItem"/>.
		/// The return item could be null if there isn't items into the repository.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="numberOfItemsToRetireve"/> is lesser than 1.</exception>
		public virtual IList<TagDto> GetTopTags(int numberOfItemsToRetireve, bool includeFuturesPosts, bool enableTracking)
		{
			Ensure.That ( numberOfItemsToRetireve )
				.Named ( "numberOfItemsToRetireve" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid number of items to retireve." );

			ICriteria myCriteria = Session.CreateCriteria<TagItem> ( );

			DetachedCriteria dtc = DetachedCriteria.For<Item> ( );
			dtc.SetProjection ( Projections.Property ( "Tags" ) );

			myCriteria.Add ( Subqueries.PropertyIn ( "Item", dtc ) );

			ProjectionList projection = Projections.ProjectionList ( )
				.Add ( Projections.Count ( "Name" ), "Count" )
				.Add ( Projections.GroupProperty ( "Name" ) );

			myCriteria.SetProjection ( projection )
				.SetMaxResults ( numberOfItemsToRetireve )
				.AddOrder ( new Order ( "Count", false ) )
				.SetCacheRegion ( CacheRules.Regions.Tolerant )
				.SetCacheable ( base.UseCache );

			IEnumerable<object[]> returnItems = myCriteria.Future<object[]> ( );

			return returnItems.Select ( t => new TagDto ( ( string )t[1], ( int )t[0] ) ).ToList ( );
		}
	}
}
